#!/usr/bin/env python3
import os
import ast
import sys

try:
    import stdlib_list
except ImportError:
    print("缺少 stdlib-list 包，请先运行: pip install stdlib-list")
    sys.exit(1)

# 项目路径（改成你自己的）
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))

# 获取当前 Python 版本的标准库
py_version = f"{sys.version_info.major}.{sys.version_info.minor}"
stdlibs = set(stdlib_list.stdlib_list(py_version))

imports = set()

# 遍历项目所有 .py 文件
for root, dirs, files in os.walk(PROJECT_DIR):
    for f in files:
        if f.endswith(".py"):
            path = os.path.join(root, f)
            try:
                with open(path, "r", encoding="utf-8") as fh:
                    tree = ast.parse(fh.read(), filename=path)
                for node in ast.walk(tree):
                    if isinstance(node, ast.Import):
                        for alias in node.names:
                            imports.add(alias.name.split(".")[0])
                    elif isinstance(node, ast.ImportFrom):
                        if node.module:
                            imports.add(node.module.split(".")[0])
            except Exception as e:
                print(f"[WARN] 解析 {path} 出错: {e}", file=sys.stderr)

# 过滤掉标准库
third_party = [i for i in imports if i not in stdlibs]

# 输出 requirements.auto.txt
outfile = os.path.join(PROJECT_DIR, "requirements.txt")
with open(outfile, "w", encoding="utf-8") as f:
    for pkg in sorted(third_party):
        f.write(pkg + "\n")

print(f"已生成 {outfile}，包含以下依赖：")
print("\n".join(third_party))
